from langchain_neo4j import Neo4jGraph
from dotenv import load_dotenv
import os

class ShareholderNodeService:
    def __init__(self):
        load_dotenv()
        #连接Neo4j数据库
        self.graph = Neo4jGraph(
            url=os.getenv("NEO4J_URI"),
            username=os.getenv("NEO4J_USERNAME"),
            password=os.getenv("NEO4J_PASSWORD"),
        )
    #创建节点
    def create_shareholder_node(self,**kwargs):
        try:
            cypher_str = "CREATE (s:Shareholder {id_no:$id_no, nationality:$nationality, is_controlled:$is_controlled, name:$name, type:$type})"
            self.graph.query(cypher_str,params=kwargs)
            return "创建节点成功"
        except Exception as e:
            print(e)
            return "创建节点失败"
    #查询节点
    def query_shareholder_node(self,**kwargs):
        try:
            cypher_str = "MATCH (s:Shareholder) RETURN s "
            data=self.graph.query(cypher_str)
            data_list=[]
            for i in range(0,len(data)):
                data_list.append(data[i]['s'])
            return data_list
        except Exception as e:
            print(e)
            return "查询失败！！！"
    #删除节点
    def delete_shareholder_node(self,**kwargs):
        try:
            cypher_str = "MATCH (s:Shareholder{id_no:$id_no}) DELETE s"
            self.graph.query(cypher_str,params=kwargs)
            return "删除节点成功"
        except Exception as e:
            print(e)
            return "删除节点失败"

    #如果股东节点不存在，则创建；如果已存在，则更新（或只更新某些字段）
    def update_shareholder_node(self,**kwargs):
        try:
            cypher_str = """
               MERGE (s:Shareholder {id_no:$id_no})
               ON CREATE SET 
                   s.id_no=$id_no,
                   s.nationality=$nationality,
                   s.is_controlled=$is_controlled, 
                   s.name=$name, 
                   s.type=$type
               ON MATCH SET 
                   s.id_no=$id_no,
                   s.nationality=$nationality,
                   s.is_controlled=$is_controlled, 
                   s.name=$name, 
                   s.type=$type
               """
            self.graph.query(cypher_str, params=kwargs)
            return "更新节点成功"
        except Exception as e:
            print(e)
            return "更新节点失败"

# if __name__ == '__main__':
#     a = CompanyNodeService()
#     data=a.query_company_node()
#     print(data)


